<?php
declare (strict_types=1);

namespace app\adminapi\controller;

use app\adminapi\business\GoodsBusiness;
use app\BaseController;
use app\common\model\SpecValue;
use think\exception\ValidateException;
use think\Request;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Log;
use think\facade\Db;

class Goods extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        try {
//
            # 调用业务逻辑层、进行操作
            $data = GoodsBusiness::list();

            return  success($data);

        }catch (\Exception $exception) {
            return  error($exception->getMessage(),$exception->getCode());
        }

    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $param = $request->all();
        try {
            # 表单验证
            $rules = [//规则
                'goods_name' => 'require|max:50|unique:goods',
                'goods_number' => 'require|number',
                'goods_logo' => 'require',
                'is_on_sale' => 'require|in:0,1',
                'goods_price' => 'require|float',
                'attr' => 'array',//商品的属性信息
                'item' => 'array',//商品规格的信息
            ];
            $message = [//错误信息
                'goods_name.require' => '商品名称必填',
                'goods_name.max' => '商品名称最多不能超过50个字符',
                'goods_number.require' => '商品库存必填',
                'goods_number.number' => '商品库存只能是数字',
                'goods_logo.require' => '商品logo必填',
                'is_on_sale.require' => '商品状态必填',
                'goods_price.require' => '商品价格必填',
                'attr.array' => '商品的属性必须是数组',
                'item.array' => '商品的规格信息必须是数组',
            ];
            $this->validate($param, $rules, $message);

            // 验证图片logo以及商品相册信息
            // 判断文件是否存在
            if (!file_exists($param['goods_logo'])) {
                abort(2001,'商品logo不存在');
            }
            // 判断商品相册
            foreach ($param['goods_images'] as $key => $path) {
                if (!file_exists($path)) {
                    unset($param['goods_images'][$key]);// 删除相册中不存在的图片
                }
            }
            // 判断是否有相册数据
            if (count($param['goods_images']) == 0) {
                abort(2001,"相册不能为空");
            }


            // 验证规格值的信息是否正确
            $values_ids = array_keys($param['item']);
            //["93_95","94_95","93_96","94_96"]
            // 把上面的数组转化为下面的数组
            //[93,95,96,94]
            $values_ids = array_unique(explode("_",implode("_",$values_ids)));
            $spec_value_count = SpecValue::whereIn('id',$values_ids)->count();
            if (count($values_ids) != $spec_value_count) {
                abort(2001,"规格信息有误、请确认后重新提交");
            }


            GoodsBusiness::save($param);

            return success();
        } catch (ValidateException $validateException) {
            return error($validateException->getError(), 2001);
        }catch (\Exception $exception) {
            return  error($exception->getMessage(),$exception->getCode());
        }

    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        try {

            $info = GoodsBusiness::detail($id);

            return  success($info);

        }catch (\Exception $exception) {
            return  error($exception->getMessage(),$exception->getCode());
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        try {

            $info = GoodsBusiness::editor($id);

            return  success($info);

        }catch (\Exception $exception) {
            return  error($exception->getMessage(),$exception->getCode());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
        try {

            if (!is_numeric($id)) {
                abort(2001,"id参数不正确");
            }
            // 上架的商品不能删除
            $is_on_sale = \app\common\model\Goods::where('id','=',$id)->where('is_on_sale','=',1)->count();
            if ($is_on_sale > 0) {
                abort(2001,'该商品已上架、不能删除');
            }

            GoodsBusiness::delete($id);

            return  success();

        }catch (\Exception $exception) {
            return  error($exception->getMessage(),$exception->getCode());
        }
    }


    /**
     * 商品审核接口
     */
    public function auditing($id,$is_recommend)
    {
        try {

            \app\common\model\Goods::where('id',$id)->update(['is_recommend' => $is_recommend]);
            Log::info("审核了商品、商品id：".$id);
            return success();

        } catch (\Exception $exception) {
            return error($exception->getMessage(), $exception->getCode());
        }
    }
}
